package com.airpi.connectivity;

import com.airpi.R;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

/**
 * Progress dialog fragment that tells the user that the Raspberry Pi is being searched
 * @author Romain Pellerin
 */
public class SearchingRaspberryDialogFragment extends DialogFragment {
	
	private static RaspberryPiDiscoverer rpd;
	
	private int message = 0;
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		ProgressDialog dialog = new ProgressDialog(getActivity());
		dialog.setMessage(getString(R.string.login_searching_pi));
		dialog.setIndeterminate(false);
		dialog.setProgressNumberFormat("%1d "+getString(R.string.login_dialog_progress)+" %2d");
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setCancelable(false);
		if (rpd != null) {
			rpd.attach(this);
			int max;
			if ((max = rpd.getMax()) != 0)
				dialog.setMax(max);
		}
		return dialog;
	}
	
	@Override
	public ProgressDialog getDialog() {
		return (ProgressDialog) super.getDialog();
	}
	
	/**
	 * Dismiss the dialog
	 * @param messageId The message to display to the user
	 */
	public void dismiss(int messageId) {
		this.message = messageId;
		this.dismiss();
	}
	
	@Override
	public void onDismiss(DialogInterface dialog) {
		if (this.message == 0) this.message = R.string.login_searching_aborted;
		rpd.setIsCancelled(true);
		super.onDismiss(dialog);
	}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if (message != 0) Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
	}

	public static void attach(RaspberryPiDiscoverer raspberryPiDiscoverer) {
		rpd = raspberryPiDiscoverer;
	}
}
